#!coding:utf8
'''
Created on Aug 7, 2012

@author: join
'''
from lottery_jx.common import tools, utils, Constant
from lottery_jx.models import Account, Trade
from django.db import transaction
import datetime
import logging
import types
from django.db.models.query_utils import Q
from lottery_jx.rpc import rpc
from django import forms
import tempfile
import os
import time

type_dict = {Constant.SHOP_ACCOUNT:u'店主', Constant.AGENT_ACCOUNT:u'代理商', Constant.TIANFU_ACCOUNT:u'添福公司'}
type_dict1 = {Constant.TRADE_ACTION:u'等待审批', Constant.TRADE_FAILED:u'审批未通过', Constant.TRADE_SUCCESSED:u'审批通过', Constant.TRADE_CENCELED:'交易取消',Constant.TRADE_SUCC:u'提现成功'}
type_dict2 = {Constant.RECHARGE:u'充值', Constant.BUY_LOTTERY:u'购买彩票', Constant.TO_CASH:u'提现', Constant.BACK_AWARD:'返奖'}

LOG = logging.getLogger('console')

@tools.render
def static_href(request,href):
    '''返回静态页面'''
    return 'account/%s.html' % href


@tools.render
def add_ac(request):
    '''返回静态页面'''
    try:
        account = Account.objects.filter(deleted=False,accountType=1).all()
        cm = []
        if len(account) > 0:
            for acc in account:        
                cm.append({'id':acc.id,
                           'loginname':acc.loginname,
                           })
        result = {'account1':cm}
        return 'account/add_account.html' ,result
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500     

    
@tools.ajaxrender
def add_account(request):
    '''注册额度账户'''
    try:
        accounts = request.POST.get('account')
        balance = request.POST.get('balance')
        name = request.POST.get('name')
        identify = request.POST.get("identify") 
        loginname = request.POST.get('loginname')
        account_type = request.POST.get('account_type')
        ratio =request.POST.get('ratio')  
        bank_num = request.POST.get("bank_num")  
        bankname =request.POST.get('bankname')  
        address = request.POST.get("address")
        telephone = request.POST.get("telephone") 
        account1 = Account.objects.filter(deleted=False).all()  
        account = Account()
        if not loginname or loginname == 'None':
            loginname = accounts        
        for acc in account1: 
            if acc.account == accounts:
                return u'新增失败,额度帐号已存在',500
            if acc.loginname == loginname :
                return u'新增失败,登录名已存在',500
            else:
                pass
        account.loginname = loginname  
        account.account = accounts
        account.password = tools.getMD5Str('123456')
        account.balance = balance
        account.name = name
        account.identify = identify
        account.bankname = bankname
        account.address = address
        account.telephone = telephone
    
        W = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
        T = ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2']
        if (len(identify) != 18):
            return u'身份证必须为18位的字符',400 
        sum = 0
        for i in range(17):
            sum += int(identify[i])*W[i]
        if  T[sum%11] == identify[17]:
            account.identify=identify
        else:
            return u'不是合法的身份证',400 
        account.commissionRatio = ratio
        account.bankNum = bank_num
        account.accountType = int(account_type )
        if account.accountType == 0:
            mac = request.POST.get("mac")
            agent = int(request.POST.get("agent") )
            if not mac or mac == 'None':
                return u'店主账户,机器编码不能为空',500
            if  agent != -1:
                account.parentid = agent
            account2 = Account.objects.filter(deleted=False).all()
            for acc in account2:
                if mac == acc.mac:
                    return u'新增失败,机器编码重复',500
                else:
                    account.mac = mac               
        account.save()    
        return u'注册成功',200
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500    


@tools.render
def listAcc(request):
    '''显示账户列表''' 
    try:
        account = Account.objects.filter(deleted=False,id=request.session['user'].id).all() 
        account = account[0]   
        return 'account/accountLists.html',{'datagrid_id':'accounts_grid','account':account}
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500    


@tools.render
def listAcc1(request):
    '''充值成功返回页面'''    
    return 'account/after_recharge.html',{'datagrid_id':'accounts_1111'}


@tools.render
def company_recharge(request):
    '''显示账户充值页面'''       
    return 'account/company_recharge.html',{'datagrid_id':'acc_2222'}


@tools.render
def update_recharge(request):
    '''显示账户充值页面'''       
    return 'account/update_recharge.html',{'datagrid_id':'acc_1111'}


@tools.ajaxrender
def search(request):
    '''显示账户列表'''
    try:
        value=request.POST.get('account')
        result = {}
        accounts = Account.objects.filter(deleted=False,account=value).all()
        if len(accounts)>0:
            rt = []
            for a in accounts:
                if not a.name or a.name == 'None':
                    a.name='暂未填写' 
                if not a.identify or a.identify == 'None':
                    a.identify='暂未填写' 
                if not a.commissionRatio or a.commissionRatio == 'None':
                    a.commissionRatio='0.0' 
                if not a.balance or a.balance == 'None':
                    a.balance='0.0' 
                rt.append({'id':a.id,
                           'account':a.account,
                           'name':a.name,
                           'identify':a.identify,
                           'balance':a.balance,
                           'commissionRatio':a.commissionRatio,
                           'accountType':type_dict.get(a.accountType)
                           })
            result['accounts'] = rt
            return result,200
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500    
    
 
@tools.ajaxrender
def search22(request):
    '''查询福彩中心余额'''
    try:
        result = {}
        res_xml = rpc.queryBalance()
        dom = rpc.parseXml2dom(res_xml)
        terms = dom.getElementsByTagName('term')
        balance = 0.0
        for term in terms:
            balance += float(term.getAttribute('balance'))
        
        result['balance'] = balance
        return result, 200
    except Exception as e:
        LOG.exception("网络异常，调用福彩中心接口失败: " % e)
        return u'系统异常，更新失败', 500    

    
@tools.ajaxrender
def surerechage(request):
    '''充值'''
    try:
        value=request.POST.get('account')
        value1=request.POST.get('money')
        money=int(value1)
        result={}
        accounts = Account.objects.filter(deleted=False,account=value).all()
        account = accounts[0]
        balance = account.balance+money
        account.balance = balance
        account.save()
        rt = []
        for a in accounts:
            rt.append({'id':a.id,
                       'account':a.account,
                       'name':a.name,
                       'identify':a.identify,
                       'balance':a.balance,
                       'commissionRatio':a.commissionRatio,
                       'accountType':a.accountType
                       })
        result['accounts'] = rt
        result['money'] = money
        return result,200
    except Exception as e:
        print str(e)



@tools.ajaxrender
def accDatalist(request):
    '''查询出所有账户信息，并显示到页面'''
    try:
        page = int(request.POST.get('page', 1))
        rows = int(request.POST.get('rows', 20))
        query_key = request.POST.get('query_key', None)
        query_value = request.POST.get('query_value', None)       
        user = request.session['user']  #TODO:权限的控制 
        accountType=user.accountType
        if  accountType == 2:
            params = {'deleted': 0}
            if query_key and query_value:
                params.update({'%s__contains' % query_key: query_value})   
            count = Account.objects.filter(**params).count()
            datas = Account.objects.filter(**params).order_by('-created_at')[(page-1)*rows: page*rows]
            return _construct_data(datas,count)
        if  accountType == 0:
            params = {'id':user.id}
            if query_key and query_value:
                params.update({'%s__contains' % query_key: query_value})   
            count = Account.objects.filter(**params).count()
            datas = Account.objects.filter(**params)[(page-1)*rows: page*rows]
            return _construct_data(datas,count)
        if  accountType == 1:
            params = {'deleted': 0}
            if query_key and query_value:
                params.update({'%s__contains' % query_key: query_value})   
            count = Account.objects.filter(Q(parentid=user.id)|Q(id=user.id)).filter(**params).count()
            datas = Account.objects.filter(Q(parentid=user.id)|Q(id=user.id)).filter(**params)[(page-1)*rows: page*rows]
            return _construct_data(datas,count)   
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500    


@tools.ajaxrender
def after_recharge(request):
    '''充值后，查询出所有账户余额信息，并显示到页面'''
    try:
        page = int(request.POST.get('page', 1))
        rows = int(request.POST.get('rows', 20))
        query_key = request.POST.get('query_key', None)
        query_value = request.POST.get('query_value', None)  
        params = {'deleted': 0}
        if query_key and query_value:
            params.update({'%s__contains' % query_key: query_value})   
        count = Account.objects.filter(**params).count()
        datas = Account.objects.filter(**params)[(page-1)*rows: page*rows]
        if datas:
            data_list = []
            for data in datas:
                data_list.append({'account_num': data.account,
                                  'loginname': data.loginname,
                                  'identify': data.identify,
                                  'balance': str(data.balance),
                                  'accountType': type_dict.get(data.accountType)})                 
            values = {'total':count,
                      'rows': data_list,
                     }
            return values
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500  
 

@tools.render
def showAccEdit(request,accId):
    '''显示修改额度账户信息页面'''
    try:
        account = Account.objects.filter(id=int(accId),deleted=False)
        account3 = Account.objects.filter(id=account[0].parentid,deleted=False)
        account2 = Account.objects.filter(accountType=1,deleted=False)
        account1 = request.session['user']
        if not account:
            return u'额度账户不存在',500     
        if account1.accountType == 2 or account[0].id == account1.id:
            account = account[0]
            if not account.address or account.address == 'None':
                account.address1=''
            else:
                account.address1=account.address 
            if not account.bankname or account.bankname == 'None':
                account.bankname1=''
            else:
                account.bankname1=account.bankname  
            if not account.telephone or account.telephone == 'None':
                account.telephone1=''
            else:
                account.telephone1=account.telephone   
            if not account.bankNum or account.bankNum == 'None':
                account.bankNum1=''
            else:
                account.bankNum1=account.bankNum   
            account.accountTypeDesc = type_dict.get(account.accountType)  
            account.accountTypedouble = account.accountType + 10 
            agents = Account.objects.filter(deleted=False, accountType=Constant.AGENT_ACCOUNT)  
            types = []
            types.append({'key':account.accountType,'value':type_dict.get(account.accountType)})
            for key in type_dict.keys():
                if key is not account.accountType:
                    types.append({'key':key,'value':type_dict.get(key)})        
            return 'account/_modify.html',{'datagrid_id':'accounts_grid','account':account, 'agents':agents, 'types':types ,'account11':account1,'account22':account2,'account33':account3}
        else:
            pass
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500          
 
 
@tools.render
def showmess(request,accId):
    '''显示额度账户详细信息页面'''
    try:
        account = Account.objects.filter(id=int(accId),deleted=False)
        account = account[0]
        account.accountTypeDesc = type_dict.get(account.accountType)
        if not account.parentid or account.parentid == 'None':
            parent = "无"
        else:
            account1 = Account.objects.filter(id=account.parentid,deleted=False)
            parent = account1[0].loginname
        if not account.mac or account.mac == 'None':
            account.mac = "无"
        else:
            account.mac = account.mac
        if not account.address or account.address == 'None':
            account.address1='暂未填写'
        else:
            account.address1=account.address 
        if not account.bankname or account.bankname == 'None':
            account.bankname1='暂未填写'
        else:
            account.bankname1=account.bankname  
        if not account.telephone or account.telephone == 'None':
            account.telephone1='暂未填写'
        else:
            account.telephone1=account.telephone   
        if not account.bankNum or account.bankNum == 'None':
            account.bankNum1='暂未填写'
        else:
            account.bankNum1=account.bankNum   

#        account3 = Account.objects.filter(id=account[0].parentid,deleted=False)
#        account2 = Account.objects.filter(accountType=1,deleted=False)
#        account1 = request.session['user']
#        if not account:
#            return u'额度账户不存在',500     
#        if account1.accountType == 2 or account[0].id == account1.id:
#            account = account[0]
#            if not account.address or account.address == 'None':
#                account.address1=''
#            else:
#                account.address1=account.address 
#            if not account.bankname or account.bankname == 'None':
#                account.bankname1=''
#            else:
#                account.bankname1=account.bankname  
#            if not account.telephone or account.telephone == 'None':
#                account.telephone1=''
#            else:
#                account.telephone1=account.telephone   
#            if not account.bankNum or account.bankNum == 'None':
#                account.bankNum1=''
#            else:
#                account.bankNum1=account.bankNum   
#            account.accountTypeDesc = type_dict.get(account.accountType)  
#            account.accountTypedouble = account.accountType + 10 
#            agents = Account.objects.filter(deleted=False, accountType=Constant.AGENT_ACCOUNT)  
#            types = []
#            types.append({'key':account.accountType,'value':type_dict.get(account.accountType)})
#            for key in type_dict.keys():
#                if key is not account.accountType:
#                    types.append({'key':key,'value':type_dict.get(key)})        
#            return 'account/_mess.html',{'datagrid_id':'accounts_grid','account':account, 'agents':agents, 'types':types ,'account11':account1,'account22':account2,'account33':account3}
        return 'account/_mess.html',{'account':account,'parent':parent}
        
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500   


@tools.ajaxrender
def edit_account(request):
    '''提交修改信息'''
      
    try:
        accountid = request.POST.get('accountid')
        account = Account.objects.get(id=int(accountid))
        name = request.POST.get('name')
        loginname = request.POST.get('loginname')  
        bankname =request.POST.get('bankname')  
        address = request.POST.get("address")
        telephone = request.POST.get("telephone")
        if not name or name == 'None':
            return u'姓名不能为空。',400
        else:
            account.name = name
        if not bankname or bankname == 'None':
            return u'开户行不能为空。',400
        else:
            account.bankname = bankname
        if not address or address == 'None':
            return u'联系地址不能为空。',400
        else:
            account.address = address
        if not telephone or telephone == 'None':
            return u'联系电话不能为空。',400   
        else:
            account.telephone = telephone   
        if not loginname or loginname == 'None':
            return u'登录名不能为空。',400
        else:
            
            accounts = Account.objects.filter(deleted=False,loginname=loginname).all()        
            if accounts and accounts[0].id!=int(accountid):
                print '1111111' ,accounts[0].id,int(accountid)
                return u'登录名已存在，请另外选择。',400                            
            account.loginname = loginname        
        identify = request.POST.get('identify',None)      
        W = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
        T = ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2']
        if (len(identify) != 18):
            return u'身份证必须为18位的字符',400 
        sum = 0
        for i in range(17):
            sum += int(identify[i])*W[i]
        if  T[sum%11] == identify[17]:
            account.identify=identify
        else:
            return u'不是合法的身份证',400        
        bankNum = request.POST.get('bank_num',None)
        if not bankNum or bankNum == 'None':
            return u'银行卡号不能为空。',400
        else:
            account.bankNum = bankNum        
        account.commissionRatio = float(request.POST.get('ratio')) if request.POST.get('ratio',None) is not None else 0.0        
        if request.session['user'].accountType == 2:
            if int(request.POST.get('account_type1',None)) == 0:
                if int(request.POST.get('agent',None)) == -1:
                    account.parentid = None
                else:
                    account.parentid = int(request.POST.get('agent',None))
        account.save()
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500    
    return u'修改成功',200


@tools.ajaxrender
@transaction.commit_on_success
def deleteAccount(request):
    '''删除额度账户'''
    try:
        ids = request.POST.getlist('id')
        for accid in ids:
            account = Account.objects.get(id=int(accid))
            if account.id == request.session['user'].id:
                return u'不能删除当前登录用户',400
            else:
                account.delete()
        return u'删除成功',200
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500    


@tools.render
def account_detail(request):
    '''查询登录用户的详细账户信息，余额，流水情况'''
    try:
        result={}
        account = request.session['user']     
        account = Account.objects.filter(deleted=False,id = int(account.id)).all()
        if not account[0].loginname or account[0].loginname == 'None':
            account[0].loginname='N/A'
        if not account[0].name or account[0].name=='None':
            account[0].name = ''        
        years = []
        months = []    
        #年份下拉列表
        cur_year = int(str(datetime.date.today())[0:4])
        years.append({'year':cur_year})
        for y in range(cur_year-20,cur_year+1):
            if y == cur_year:
                continue
            years.append({'year':y})    
        #月份下拉列表
        cur_month = int(str(datetime.date.today())[5:7])
        months.append({'month':cur_month})
        for month in range(1,13):
            if month == cur_month:
                continue
            months.append({'month':month})   
        start_time = datetime.datetime(cur_year,cur_month,1)
        if int(month) == 12:
            end_time = datetime.datetime(cur_year+1,1,1)
        else:
            end_time = datetime.datetime(cur_year,cur_month+1,1) 
        #查询出交易数据概览
        recharges = Trade.objects.filter(accountid=account,tradeType=Constant.TRADE_RECHARGE, deleted=False,created_at__lte=end_time,
                                        created_at__gte=start_time,status=Constant.TRADE_SUCCESSED).order_by('-created_at')
        if account[0].accountType == 0: 
            withdraws = Trade.objects.filter(accountid=account,tradeType=Constant.TRADE_WITHDRAW, deleted=False,created_at__lte=end_time,
                                             created_at__gte=start_time,status=Constant.TRADE_SUCCESSED).order_by('-created_at')
        
            result['withdraws'] = withdraws
        result['years'] = years
        result['months'] = months
        account = account[0]
        account.account_type = type_dict.get(account.accountType)
        result['account'] = account
        result['recharges'] = recharges
        return 'account/_detail.html',result
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500    
    

@tools.ajaxrender
def get_trades_detail(request):
    '''获取指定月份的交易数据'''
    try:
        result = {}
        account = request.session['user']    
        year = request.POST.get("year")
        month = request.POST.get("month")   
        start_time = datetime.datetime(int(year),int(month),1)
        if int(month) == 12:
            end_time = datetime.datetime(int(year)+1,1,1)
        else:
            end_time = datetime.datetime(int(year),int(month)+1,1)    
        recharges = Trade.objects.filter(accountid=account,tradeType=Constant.TRADE_RECHARGE, deleted=False,created_at__lte=end_time,
                                         created_at__gte=start_time,status=Constant.TRADE_SUCCESSED).order_by('-created_at')
        recharge_infos = []   
        withdraw_infos = []    
        for recharge in recharges:
            recharge_infos.append({'tradeAmount':'%.1f'%recharge.tradeAmount,'tradeTime':utils.convert_datetime_to_str(recharge.tradeTime,'%Y-%m-%d %H:%M:%S')})     
        result['recharge_infos'] = recharge_infos
        if account.accountType == 0:
            withdraws = Trade.objects.filter(accountid=account,tradeType=Constant.TRADE_WITHDRAW, deleted=False,created_at__lte=end_time,
                                             created_at__gte=start_time,status=Constant.TRADE_SUCCESSED).order_by('-created_at') 
            for withdraw in withdraws:
                withdraw_infos.append({'tradeAmount':'%.1f'%withdraw.tradeAmount,'tradeTime':utils.convert_datetime_to_str(withdraw.tradeTime,'%Y-%m-%d %H:%M:%S')})        
        result['withdraw_infos'] = withdraw_infos 
        return result, 200
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500    
    


def _construct_data(datas, count):
    """
    把账户信息转成dict
    """
    try:
        if datas:
            data_list = []
            for data in datas:
                if not data.name or data.name == 'None':
                    data.name='暂未填写' 
                if not data.identify or data.identify == 'None':
                    data.identify='暂未填写' 
                if not str(data.commissionRatio) or str(data.commissionRatio) == 'None':
                    data.commissionRatio='0.0'  
                if not data.balance or data.balance == 'None':
                    data.balance='0.0' 
                if str(data.parentid) == 'None':
                    parentidname = 'None'
                else:
                    data2 = Account.objects.filter(deleted=False,id=data.parentid).all()
                    parentidname = data2[0].loginname
                   
                if not parentidname or parentidname == 'None':
                    parentidname='暂无'
           
                data_list.append({'account_num': data.account,
                                  'name': data.name,
                                  'identify': data.identify,
                                  'balance': str(data.balance),
                                  'commissionRatio': str(data.commissionRatio),
                                  'accountType': type_dict.get(data.accountType),
                                  'parentid': str(data.parentid),
                                  'parentidname': parentidname,
                                  'createtime':utils.convert_datetime_to_str(data.created_at),
                                  'updatetime':utils.convert_datetime_to_str(data.updated_at),
                                  'action':data.id,
                                  'desc': data.desc,})
            values = {'total':count,
                      'rows': data_list,
                      }
            return values
    except Exception as e:
        print str(e)
    return None   


@tools.render
def applicationcash(request):
    '''申请提现'''    
    return 'account/application-cash.html',{'datagrid_id':'grid'}
    

@tools.ajaxrender
def applications(request):
    '''查询出店主所有的提现记录，并显示到页面'''
    try:
        page = int(request.POST.get('page', 1))
        rows = int(request.POST.get('rows', 20))
        query_key = request.POST.get('query_key', None)
        query_value = request.POST.get('query_value', None)
        
        a=Account.objects.filter(deleted=False,id=request.session['user'].id).all()        
        params = {'deleted': 0,'accountid':a[0],'tradeType':2}
        if query_key and query_value:
            params.update({'%s__contains' % query_key: query_value})        
        count = Trade.objects.filter(**params).count()        
        datas = Trade.objects.filter(**params).order_by('-created_at')[(page-1)*rows: page*rows]              
        cm = []  
        a=a[0]
        if not a.name or a.name == 'None':
            a.name='暂未填写' 
        if not a.identify or a.identify == 'None':
            a.identify='暂未填写'       
        for data in datas: 
#            if data.status == 1:
#                if not data.approver or data.approver == 'None':
#                    loginname1=''
#                else :
#                    loginname1= data.approver.loginname
#            elif data.status == 4:
#                if not data.cashier or data.cashier == 'None':
#                    loginname1=''
#                else :
#                    loginname1= data.cashier.loginname 
#            else:
#                loginname1=''        
            cm.append({'id':data.id,
                       'tradeType':type_dict2.get(data.tradeType),
                       'tradeMethod':data.tradeMethod,
                       'tradeAmount':data.tradeAmount,
                       'desc':data.desc,
#                       'approver':loginname1,
                       'accountid':a.account,
                       'tradeTime':utils.convert_datetime_to_str(data.tradeTime, '%Y-%m-%d %H:%M:%S'),
                       'status':type_dict1.get(data.status),
                       'name':a.name,
                       'identify': a.identify})    
        result= {'total':count,
                 'rows': cm}   
        return result
    except Exception as e:
        print str(e)


@tools.ajaxrender
def update_re(request):
    '''查询出店主所有的充值记录，并显示到页面'''
    try:
        page = int(request.POST.get('page', 1))
        rows = int(request.POST.get('rows', 20))
        query_key = request.POST.get('query_key', None)
        query_value = request.POST.get('query_value', None)
        a=Account.objects.filter(deleted=False,id=request.session['user'].id).all()      
        params = {'deleted': 0,'accountid':a[0],'tradeType':0}
        if query_key and query_value:
            params.update({'%s__contains' % query_key: query_value})       
        count = Trade.objects.filter(**params).count()       
        datas = Trade.objects.filter(**params).order_by('-created_at')[(page-1)*rows: page*rows]
        cm = []  
        a=a[0]
        if not a.name or a.name == 'None':
            a.name='暂未填写' 
        if not a.identify or a.identify == 'None':
            a.identify='暂未填写'      
        for data in datas:           
            cm.append({'id':data.id,
                       'tradeType':type_dict2.get(data.tradeType),
                       'tradeMethod':data.tradeMethod,
                       'tradeAmount':data.tradeAmount,
                       'desc':data.desc,
                       'accountid':a.account,
                       'tradeTime':utils.convert_datetime_to_str(data.tradeTime, '%Y-%m-%d %H:%M:%S'),
                       'status':type_dict1.get(data.status),
                       'name':a.name,
                       'identify': a.identify})   
        result= {'total':count,
                 'rows': cm}   
        return result
    except Exception as e:
        print str(e)



@tools.ajaxrender
def company_re(request):
    '''查询出店主所有的待审批充值记录，并显示到页面'''
    try:
        page = int(request.POST.get('page', 1))
        rows = int(request.POST.get('rows', 20))
        query_key = request.POST.get('query_key', None)
        query_value = request.POST.get('query_value', None) 
        print query_key,query_value
        cm = []    
        params = {'deleted': 0,'status':0,'tradeType':0}
        if query_key and query_value:
            params.update({'accountid__%s__contains' % query_key: query_value})       
        count = Trade.objects.filter(**params).count()       
        datas = Trade.objects.filter(**params).order_by('-created_at')[(page-1)*rows: page*rows]        
        datas1=datas[0]
        if not datas1.accountid.name or datas1.accountid.name == 'None':
            datas1.accountid.name='暂未填写' 
        if not datas1.accountid.identify or datas1.accountid.identify == 'None':
            datas1.accountid.identify='暂未填写'           
        for data in datas: 
                           
            cm.append({'id':data.id,
                       'tradeType':type_dict2.get(data.tradeType),
                       'tradeMethod':data.tradeMethod,
                       'tradeAmount':data.tradeAmount,
                       'desc':data.desc,
                        'accountid':data.accountid.account,
                        'tradeTime':utils.convert_datetime_to_str(data.tradeTime, '%Y-%m-%d %H:%M:%S'),
                        'status':type_dict1.get(data.status),
                        'name':data.accountid.name,
                        'identify': data.accountid.identify}) 
        result= {'total':count,
                 'rows': cm}    
        return result
    except Exception as e:
        print str(e)


@tools.ajaxrender
def history_record(request):
    '''查询出公司处理的提现记录，并显示到页面'''
    try:
        page = int(request.POST.get('page', 1))
        rows = int(request.POST.get('rows', 15))
        query_key = request.POST.get('query_key', None)
        query_value = request.POST.get('query_value', None)
        cm = []  
        params = {'deleted': 0,'tradeType':2}
        if query_key and query_value:
            params.update({'accountid__%s__contains' % query_key: query_value})
        
        count = Trade.objects.filter(Q(status=1)|Q(status=4)).filter(**params).count()
        datas = Trade.objects.filter(Q(status=1)|Q(status=4)).filter(**params).order_by('-created_at')[(page-1)*rows: page*rows]      
              
        for data in datas:
            if not data.accountid.name or data.accountid.name == 'None':
                data.accountid.name='暂未填写' 
            if not data.accountid.identify or data.accountid.identify == 'None':
                data.accountid.identify='暂未填写'
        
       
            if  data.status == 1:
                if not data.approver or data.approver == 'None':
                    loginname1 = ''                    
                else:                    
                    loginname1 =data.approver.loginname                 
            if  data.status == 4:
                if not data.cashier or data.cashier == 'None':
                    loginname1 = ''
                    
                else:
                    loginname1 = ''
                    if not data.approver or data.approver == 'None':
                        loginname1 =['审批(无)','返现',data.cashier.loginname ] 
                    else:   
                        loginname1 =['审批',data.approver.loginname,'返现', data.cashier.loginname ]   
            cm.append({'id':data.id,
                       'tradeType':type_dict2.get(data.tradeType),
                       'tradeMethod':data.tradeMethod,
                        'tradeAmount':data.tradeAmount,
                        'loginname1':loginname1,
                        'desc':data.desc,
                        'accountid':data.accountid.account,
                        'tradeTime':utils.convert_datetime_to_str(data.tradeTime, '%Y-%m-%d %H:%M:%S'),
                        'status':type_dict1.get(data.status),
                        'name':data.accountid.name,
                        'identify': data.accountid.identify}) 
        result= {'total':count,
                 'rows': cm}    
        return result
    except Exception as e:
        print str(e)


@tools.ajaxrender
def withdraws(request):
    '''查询出所有的未处理提现记录，并显示到页面'''
    try:
        page = int(request.POST.get('page', 1))
        rows = int(request.POST.get('rows', 15))
        query_key = request.POST.get('query_key', None)
        query_value = request.POST.get('query_value', None)
    #    user = request.session['user']  #TODO:权限的控制
        cm = [] 
        params = {'deleted': 0,'tradeType':2}
        if query_key and query_value:
            params.update({'accountid__%s__contains' % query_key: query_value})
        count = Trade.objects.filter(Q(status=0)|Q(status=2)).filter(**params).count()
        datas = Trade.objects.filter(Q(status=0)|Q(status=2)).filter(**params).order_by('-created_at')[(page-1)*rows: page*rows]          
        for data in datas:
            if not data.accountid.loginname or data.accountid.loginname == 'None':
                data.accountid.loginname='暂未填写'
            if not data.accountid.name or data.accountid.name == 'None':
                data.accountid.name='暂未填写' 
            if not data.accountid.identify or data.accountid.identify == 'None':
                data.accountid.identify='暂未填写' 
            
            if not data.approver or data.approver == 'None':
                loginname='' 
            else:
                loginname=data.approver.loginname
                 
            cm.append({'id':[data.id,data.status],
                        'tradeType':type_dict2.get(data.tradeType),
                        'approver':loginname,
                        'tradeMethod':data.tradeMethod,
                        'tradeAmount':data.tradeAmount,
                        'accountid':data.accountid.account,
                        'tradeTime':utils.convert_datetime_to_str(data.tradeTime, '%Y-%m-%d %H:%M:%S'),
                        'status':type_dict1.get(data.status),
                        'name':data.accountid.name,
                        'loginname':data.accountid.loginname,
                        'identify': data.accountid.identify})  
        result= {'total':count,
                 'rows': cm}    
        return result
    except Exception as e:
        print str(e)


@tools.render
def add_application(request):   
    '''申请提现'''
    try:
        account=request.session['user'].account
        a=Account.objects.filter(deleted=False,account=account).all()
        a=a[0]
        if not a.name or a.name == 'None':
            a.name='暂未填写' 
        if not a.identify or a.identify == 'None':
            a.identify='暂未填写' 
        if not a.commissionRatio or a.commissionRatio == 'None':
            a.commissionRatio='0.0' 
        if not a.parentid or a.parentid == 'None':
            a.parentid='暂未填写' 
        if not a.balance or a.balance == 'None':
            a.balance='0.0' 
        result={'account':a.account,
            'name':a.name,
            'identify':a.identify,
            'balance':a.balance,
            'commissionRatio':a.commissionRatio,
            'accountType':type_dict.get(a.accountType)}
        return 'account/add_application.html',result
    except Exception as e:
        print str(e)       
        
        
@tools.render
def add_recharge(request):
    
    '''申请充值'''
    try:
        account=request.session['user'].account
        a=Account.objects.filter(deleted=False,account=account).all()
        a=a[0]
        if not a.name or a.name == 'None':
            a.name='暂未填写' 
        if not a.identify or a.identify == 'None':
            a.identify='暂未填写' 
        if not a.commissionRatio or a.commissionRatio == 'None':
            a.commissionRatio='0.0' 
        if not a.parentid or a.parentid == 'None':
            a.parentid='暂未填写' 
        if not a.balance or a.balance == 'None':
            a.balance='0.0' 
        result={'account':a.account,
            'name':a.name,
            'identify':a.identify,
            'balance':a.balance,
            'commissionRatio':a.commissionRatio,
            'accountType':type_dict.get(a.accountType)}
        return 'account/add_recharge.html',result
    except Exception as e:
        print str(e)        
        

@tools.ajaxrender
def recharge_add(request):
    '''增加申请充值'''
    try:
        tradeAmount = request.POST.get('input7')
        tradeAmount=int(tradeAmount)  
        if 0<tradeAmount :    
            trade = Trade()
            trade.tradeType = 0      
            trade.tradeAmount=tradeAmount       
            trade.accountid = request.session['user']       
            trade.tradeTime =utils.utcnow()       
            trade.status = 0           
            trade.save()
            return u'申请成功',200
        else:
            return 'error',500
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500    


@tools.ajaxrender
def application_add(request):
    '''增加申请提现'''
    try:
        tradeAmount = request.POST.get('input7')
        tradeAmount=float(tradeAmount)
        account = Account.objects.filter(deleted=False,id=request.session['user'].id).all()
        account = account[0]
        if 0<tradeAmount < request.session['user'].balance:
            account.balance=account.balance-tradeAmount        
            account.save()
            trade = Trade()
            trade.tradeType = 2
            trade.tradeAmount = tradeAmount
            trade.accountid = request.session['user']
            trade.tradeTime =utils.utcnow()
            trade.status = 0  
            trade.save()
            return u'申请成功',200
        else:
            return 'error',500  
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500     


@tools.render
def accountwithdraws(request):
    '''处理提现'''   
    return 'account/account-withdraws.html',{'datagrid_id':'accounts'}


@tools.ajaxrender
def agree_application(request):
    '''同意申请'''  
    try:
        id = request.POST.get('id')
        id = int(id)
        tr=Trade.objects.filter(deleted=False,id=id).all()   
        trade=tr[0]
        trade.status=2 
        trade.approver=request.session['user']
        trade.save()   
        return u'交易成功',200
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500    



@tools.ajaxrender
def refuse_application(request):
    '''拒绝申请'''
    try:
        desc=request.POST.get('desc')    
        id = request.POST.get('id')
        id =int(id) 
        tr=Trade.objects.filter(deleted=False,id=id).all() 
        ac=Account.objects.filter(deleted=False,id=tr[0].accountid.id).all()
        ac=ac[0]
        ac.balance=ac.balance+tr[0].tradeAmount
        ac.save()
        trade=tr[0]
        trade.status=1 
        trade.desc=desc 
        trade.approver=request.session['user']       
        trade.save()  
        return u'操作成功',200
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500    


@tools.render
def refuse(request,id):
    '''显示拒绝原因页面'''
   
    return 'account/refuse.html',{'recordid':id}


@tools.render
def history_record0(request):
    '''显示公司历史处理提现记录'''
    
    return 'account/history_record.html',{'datagrid_id':'acc'}


@tools.ajaxrender
def agree_recharge(request):
    '''同意充值'''  
    try:
        id = request.POST.get('id')
        id = int(id)
        tr=Trade.objects.filter(deleted=False,id=id).all()   
        trade=tr[0]
        trade.status=2 
        id1=trade.accountid.id
        a=Account.objects.filter(deleted=False,id=id1).all()
        account = a[0]
        account.balance=account.balance+trade.tradeAmount
        account.save()  
        trade.save()   
        return u'交易成功',200
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500    


@tools.ajaxrender
def refuse_reason(request):
    '''拒绝充值'''
    try:
        desc=request.POST.get('desc')    
        id = request.POST.get('id')
        id =int(id) 
        tr=Trade.objects.filter(deleted=False,id=id).all() 
        trade=tr[0]
        trade.status=1 
        trade.desc=desc      
        trade.save()  
        return u'操作成功',200
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500    


@tools.render
def refuse_recharge(request,id):
    '''显示拒绝充值原因页面'''
    
    return 'account/refuse_reason.html',{'recordid':id}


@tools.render
def history_recharge(request):
    '''显示公司历史处理充值记录'''
    
    return 'account/history_recharge.html',{'datagrid_id':'acc_33333'}

@tools.ajaxrender
def history_re(request):
    '''查询出所有的充值记录，并显示到页面'''
    try:      
        page = int(request.POST.get('page', 1))
        rows = int(request.POST.get('rows', 20))
        query_key = request.POST.get('query_key', None)
        query_value = request.POST.get('query_value', None)   
        params = {'deleted': 0,'tradeType':0}
        if query_key and query_value:
            params.update({'accountid__%s__contains' % query_key: query_value})       
        count = Trade.objects.filter(**params).count()       
        datas = Trade.objects.filter(**params).order_by('-created_at')[(page-1)*rows: page*rows]
        cm = []  
        datas1=datas[0]
        if not datas1.accountid.name or datas1.accountid.name == 'None':
            datas1.accountid.name='暂未填写' 
        if not datas1.accountid.identify or datas1.accountid.identify == 'None':
            datas1.accountid.identify='暂未填写'      
        for data in datas:        
            cm.append({'id':data.id,
                       'tradeType':type_dict2.get(data.tradeType),
                       'tradeMethod':data.tradeMethod,
                       'tradeAmount':data.tradeAmount,
                       'desc':data.desc,
                       'accountid':data.accountid.account,
                       'tradeTime':utils.convert_datetime_to_str(data.tradeTime, '%Y-%m-%d %H:%M:%S'),
                       'status':type_dict1.get(data.status),
                       'name':data.accountid.name,
                       'identify': data.accountid.identify})   
        result= {'total':count,
                 'rows': cm}   
        return result
    except Exception as e:
        print str(e)


@tools.render
def myself_recharge(request):
    
    '''公司充值 页面显示'''
    try:
        account=request.session['user'].account
        a=Account.objects.filter(deleted=False,account=account).all()
        a=a[0]
        if not a.name or a.name == 'None':
            a.name='暂未填写' 
        if not a.identify or a.identify == 'None':
            a.identify='暂未填写' 
        if not a.commissionRatio or a.commissionRatio == 'None':
            a.commissionRatio='0.0' 
        if not a.parentid or a.parentid == 'None':
            a.parentid='暂未填写' 
        if not a.balance or a.balance == 'None':
            a.balance='0.0' 
        result={'account':a.account,
            'name':a.name,
            'identify':a.identify,
            'balance':a.balance,
            'commissionRatio':a.commissionRatio,
            'accountType':type_dict.get(a.accountType)}
        return 'account/myself_recharge.html',result
    except Exception as e:
        print str(e)                 
        
 
@tools.ajaxrender
def recharge_myself(request):
    '''公司充值'''
    try:
        tradeAmount = request.POST.get('value')
        tradeAmount=int(tradeAmount)
        if 0<tradeAmount :
            a=Account.objects.filter(deleted=False,id=request.session['user'].id).all()
            account = a[0]
            account.balance=account.balance+tradeAmount
            trade = Trade()
            trade.tradeType = 0
            trade.tradeAmount=tradeAmount
            trade.accountid = request.session['user']
            trade.tradeTime =utils.utcnow()
            trade.status = 2          
            account.save()     
            trade.save()
            return u'申请成功',200
        else:
            return 'error',500   
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500        
  
  
@tools.ajaxrender
def succ(request):
    '''提现完成'''  
    try:
        id = request.POST.get('id')
        id = int(id)
        tr=Trade.objects.filter(deleted=False,id=id).all()   
        trade=tr[0]
        trade.status=4  
        trade.cashier= request.session['user']
        trade.save()   
        return u'交易成功',200  
    except Exception as e:
        LOG.exception("系统发生异常，异常为：%s" % e)
        return u'系统异常，更新失败',500    

class ReportForm(forms.Form):
    reportfile = forms.FileField()
    
@tools.ajaxrender   
def handle_bank_report(req):
    '''处理上传的银行报表，根据报表上的信息进行额度账户的充值'''
    try:
        if req.method=='POST':
            form = ReportForm(req.POST,req.FILES)
        if form.is_valid():
            reportfile = req.FILES['reportfile']
            tempd=tempfile.mkdtemp()
            filepath = os.path.join(tempd,'temp_report_%s.xls'%time.time())
            if os.path.exists(filepath):
                os.remove(filepath)
            destination = open(filepath,'wb+')
            
            for chunk in reportfile.chunks():
                destination.write(chunk)
            destination.close()
            account_util = AccountUtil(filepath)
            account_util.import_bank_report()
#            tools.import_bank_report(filepath,req.session['user'])
            os.remove(filepath)
            os.removedirs(tempd)
            
            return {'message':u'导入成功.'},200
        else:
            return {'message':u'失败,路径不合法.'}, 500
    except Exception as e:
        print e
        LOG.exception('handle bank report occured exception:%s'%e)
        return u'处理报表失败', 500
        
class AccountUtil():
    def __init__(self,filepath):
        self.filepath = filepath
        
    @transaction.commit_on_success
    def import_bank_report(self):
        try:
            import xlrd 
            book = xlrd.open_workbook(self.filepath)
            sh = book.sheet_by_index(0)
    #        sh = book.sheet_by_name(dic.get(report_type))
            for rx in range(sh.nrows):
                message = sh.cell_value(rx,7)
                if not message or message.find('=') == -1:
                    continue
                account_infos = message.split('=')
                account = account_infos[0]
                money = account_infos[1]
                accounts = Account.objects.filter(account=account,deleted=0)
                if not accounts:
                    continue
                account = accounts[0]
                
                trade = Trade(tradeType=0,tradeAmount=float(money),accountid=account,tradeTime=utils.utcnow(),status=0)
                trade.save()
        except Exception as e:
            print e
            raise e
                
            
            